// pagesShangping/pages/index/index.js
const app = getApp();
import { baseUrl } from "../../../api/request";
import { getStorage } from "../../../utils/localStorage";
import {
    commodity_List, commodityTypeList, shopping_List, order_List, shoppingCartNum_opt, shoppingCart_Delete, advance_Paymen, orderTotal_money
    , shoppingCartPrice
} from "../../../api/shopping";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: baseUrl,
        //自定义导航栏参数
        navData: {
            title1: '商品',
            title2: '购物车',
            title3: '订单',
            level: 6 //导航栏级别  
        },
        pageTop: app.globalData.navHeight + app.globalData.navTop,
        pageBottom: app.globalData.bottomLift,
        userInfo: {},
        //列表搜索参数
        listQuery: {
            pageNum: 1,
            pageSize: 10,
            classifyId: "",
            goodsName: "",
        },
        total: 0,
        pageIndex: 1,
        downState: false,
        //商品模块变量
        comLeftList: [],
        comRightList: [],
        commodTypeList: [],
        comTypeIndex: 0,
        //购物车模块变量
        shoppingList: [],
        ljfkButtonState: false,
        selectAllState: false, //全选状态
        //订单模块变量
        orderList: [],
        //合计数量
        hjNum: 0,
        //选中商品数组
        shopCartArr: [],
        //订单合计金额
        totalPrice: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            userInfo: getStorage('user')
        });
        if (JSON.stringify(options) != "{}") {
            this.setData({
                pageIndex: +options.pageIndex
            });
        };
        this.getCommodityList();
        this.getCommodityTypeList();
        this.getShoppingList();
        this.getOrderList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({ shopCartArr: [] })
    },

    //导航栏点击事件
    navTap(e) {
        this.setData({
            pageIndex: e.detail,
            "listQuery.pageNum": 1,
            "listQuery.pageSize": 10,
            comLeftList: [],
            comRightList: [],
            shoppingList: [],
            orderList: [],
            totalPrice: 0
        });
        switch (this.data.pageIndex) {
            case 1:
                this.getCommodityList();
                break;
            case 2:
                this.getShoppingList();
                break;
            case 3:
                this.getOrderList();
                break;
        };
    },
    /* 下拉刷新 */
    downUp() {
        this.setData({
            downState: true,
            "listQuery.pageNum": 1,
            "listQuery.pageSize": 10,
            comLeftList: [],
            comRightList: [],
            shoppingList: [],
            orderList: [],
        });
        switch (this.data.pageIndex) {
            case 1:
                this.getCommodityList();
                break;
            case 2:
                this.getShoppingList();
                break;
            case 3:
                this.getOrderList();
                break;
        };
        setTimeout(() => {
            wx.showToast({
                icon: 'success',
                title: '下拉刷新成功',
                duration: 2000
            });
            this.setData({ downState: false, });
        }, 2000);
    },
    /* 上拉加载更多 */
    pullUp(e) {
        if ((this.data.listQuery.pageNum + 1) <= this.data.total) {
            this.setData({
                "listQuery.pageNum": this.data.listQuery.pageNum += 1
            });
            this.data.pageIndex === 1 ?  this.getCommodityList() : this.data.pageIndex === 2 ? this.getShoppingList() : this.getOrderList();
        };
    },


    /**
     *  商品模块自定义方法
     */

    //查询商品列表
    getCommodityList() {
        commodity_List(this.data.listQuery).then(res => {
            let leftArr = [], rigthArr = [];
            res.data.rows.forEach((item, index) => {
                item.imageScale = item.imageScale ? item.imageScale.split(",") : [];
                item.spingCartState = false;
                if (index % 2 === 0) {
                    leftArr.push(item);
                } else {
                    rigthArr.push(item);
                };
            });
            this.setData({
                comLeftList: [...this.data.comLeftList, ...leftArr],
                comRightList: [...this.data.comRightList, ...rigthArr],
                total: Math.ceil(res.data.total / this.data.listQuery.pageSize)
            });
        });
    },
    //查询商品分类列表
    getCommodityTypeList() {
        commodityTypeList().then(res => {
            res.data.data.unshift({ classifyName: '全部', id: 0 });
            this.setData({ commodTypeList: res.data.data });
        });
    },

    //商品搜索input框bindblur事件
    goodsNameInput(e) {
        this.setData({
            comLeftList: [],
            comRightList: [],
            "listQuery.pageNum": 1,
            "listQuery.pageSize": 10,
            "listQuery.goodsName": e.detail.value,
        });
        this.getCommodityList();
    },
    //商品分类列表点击事件
    spCommidTap(e) {
        const id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index;
        this.setData({
            comLeftList: [],
            comRightList: [],
            comTypeIndex: index,
            "listQuery.pageNum": 1,
            "listQuery.pageSize": 10,
            "listQuery.classifyId": index === 0 ? "" : id,
        });
        this.getCommodityList();
    },

    //商品列表点击事件
    commditListTap(e) {
        const item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: '/pagesShangping/pages/shoppingDetail/index?id=' + item.id,
        })
    },

    /**
      购物车模块自定义方法
    */

    //获取购物车列表
    getShoppingList() {
        this.data.listQuery.userId = this.data.userInfo.id;
        shopping_List(this.data.listQuery).then(res => {
            res.data.rows.forEach(item => {
                item.imageScale = item.imageScale ? item.imageScale.split(",") : [],
                    item.xzState = false;
            });
            this.setData({
                shoppingList: [...this.data.shoppingList, ...res.data.rows],
                total: Math.ceil(res.data.total / this.data.listQuery.pageSize)
            });
        });
    },
    //购物车列表点击事件
    shoppingListTap(e) {
        const item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: '/pagesShangping/pages/shoppingDetail/index?id=' + item.id,
        });
    },
    //购物车列表删除按钮点击事件
    listDelete(e) {
        const item = e.currentTarget.dataset.item;
        wx.showModal({
            title: '警告',
            content: `请确定是否要删除${item.goodsName}的商品`,
            complete: (res) => {
                if (res.confirm) {
                    shoppingCart_Delete(item.id).then(res => {
                        wx.showToast({
                            icon: 'none',
                            title: res.data.msg,
                            duration: 2000
                        });
                        res.data.code === 200 ? setTimeout(() => { this.setData({ shoppingList: [] }); this.getShoppingList() }, 2000) : false;
                    });
                }
            }
        })
    },
    //商品数量input框 bindinput事件
    countInput(e) {
        const num = e.detail.value, index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item;
        let value = "shoppingList[" + index + "].goodsCount";
        shoppingCartNum_opt({ goodsId: item.goodsId, userId: this.data.userInfo.id, goodsCount: num }).then(res => {
            this.setData({ [value]: num < 1 ? 1 : num });
            if (item.xzState) {
                this.getOrderTotalMoney()
            };
        });
    },
    //购物车加减数量按钮点击事件
    reduceTap(e) {
        const type = e.currentTarget.dataset.type,
            index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            value = "shoppingList[" + index + "].goodsCount";
        let num = item.goodsCount;
        type == "add" ? num++ : num <= 1 ? num = 1 : num--;
        shoppingCartNum_opt({ goodsId: item.goodsId, userId: this.data.userInfo.id, goodsCount: num }).then(res => {
            this.setData({ [value]: num });
            if (item.xzState) {
                this.getOrderTotalMoney()
            };
        });
    },
    //列表checked点击事件
    xzSpListTap(e) {
        const index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            value = "shoppingList[" + index + "].xzState",
            arr = this.data.shopCartArr;
        !item.xzState ? arr.push(item) : arr.splice(arr.findIndex(val => val.id === item.id), 1);
        this.setData({
            [value]: !item.xzState,
            shopCartArr: arr,
            selectAllState: this.data.shopCartArr.length == this.data.shoppingList.length ? true : false
        });
        this.getOrderTotalMoney();
    },
    //全选checked点击事件
    selectAllTap(e) {
        let state = e.currentTarget.dataset.state;
        let arr = this.data.shoppingList.map(item => ({
            ...item,
            xzState: !state ? true : false,
        }));
        this.setData({
            selectAllState: !state,
            shoppingList: arr,
            shopCartArr: !state ? arr : [],
            totalPrice: !state ? this.data.totalPrice : 0,
        });
        this.getOrderTotalMoney();
    },
    //查询合计金额
    getOrderTotalMoney() {
        let arr = this.data.shopCartArr.map(item => ({
            ...item,
            imageScale: item.imageScale ? item.imageScale.toString() : '',
        }));
        orderTotal_money(arr).then(res => {
            this.setData({ totalPrice: res.data.data });
        });
    },

    //立即付款按钮点击事件
    paymentTap() {
        this.setData({ ljfkButtonState: true });
        const hasState = this.data.shoppingList.some(item => item.xzState);
        if (hasState) {
            const arr = this.data.shoppingList.filter(item => item.xzState).map(val => ({ ...val, imageScale: val.imageScale ? val.imageScale.join(",") : '' }));
            advance_Paymen(arr).then(res => {
                if (res.data.code === 200) {
                    wx.navigateTo({
                        url: '/pagesShangping/pages/submitOrder/index?data=' + encodeURIComponent(JSON.stringify(res.data.data)),
                    });
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: res.data.msg,
                        duration: 2000
                    });
                };
                this.setData({ ljfkButtonState: false });
            });
        } else {
            wx.showToast({
                icon: 'none',
                title: '请先选择商品',
                duration: 2000
            });
            this.setData({ ljfkButtonState: false });
        };
    },


    /** 
     * 订单模块自定义方法
     */

    //获取订单列表
    getOrderList() {
        this.data.listQuery.userId = this.data.userInfo.id;
        order_List(this.data.listQuery).then(res => {
            res.data.rows.forEach(item => {
                item.shopOrderItems.forEach(val => {
                    val.imageScale = val.imageScale ? val.imageScale.split(",") : []
                });
            });
            console.log(res.data.rows,'ssss');
            this.setData({ 
                orderList:[...this.data.orderList,...res.data.rows],
                total: Math.ceil(res.data.total / this.data.listQuery.pageSize) 
            });
        });
    },
    //订单列表点击事件
    orderListTap(e) {
        const item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: '/pagesShangping/pages/orderDetail/index?id=' + item.id,
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})